package com.sdyeda.dtu.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sdyeda.tool.HexTools;

public class IotClientThread extends Thread {
	Object lock =0 ;
	private Socket socket = null;
	
	private final Log log = LogFactory.getLog(this.getClass());
	
	public IotClientThread(Socket socket) {
		this.socket = socket;
	}
	
	@Override
	public void run() {
		try {
			// OutputStream writer = socket.getOutputStream();
			InputStream reader = socket.getInputStream();
			//int len = 0;
			//byte[] buff = new byte[1024];
			while (true) {
				
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
				}

				int availnum = reader.available();
				if (availnum > 0) {
					byte[] buff = new byte[availnum];
					
					int ret = reader.read(buff);
					
					log.info("IOT:"+HexTools.bytesToHex(buff));
					//System.out.println(ret +"::iot::"+HexTools.bytesToHex(buff));
					if (ret > 0) {
						synchronized (lock) {
							send(buff, ret);
						}

					}
				}
				
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	void send(byte[] buff, int length) {
		List<DtuInfo> list = Server.getDtuclients();
		Server.getIotclients();
		if (list != null) {
			list.forEach(item -> {
				if (item.getSocket().isConnected() || !item.getSocket().isClosed()) {
					try {
						item.getSocket().getOutputStream().write(buff, 0, length);
					} catch (IOException e) {
						//System.out.println(e);
						try {
							//item.shutdownInput();
							item.getSocket().shutdownOutput();
							//item.close();
						} catch (IOException e1) {
							//e1.printStackTrace();
						}
						//e.printStackTrace();
					}
				}
			});
		}
	}
}
